<template>
  <div>
    <div class="d-flex mb-3">
      <h5 class="card-title">资金来源明细</h5>
      <button class="btn pt-0 btn-text text-muted" @click="breakdown()" v-if="noFile">
        <i class="fa fa-edit"></i>
      </button>
    </div>
    <loading-wrap>
      <el-table border :data="sourcesData">
        <el-table-column label="资金来源" align="center" prop="capital_source">
          <template slot-scope="scope">{{ scope.row.capital_source || '-' }}</template>
        </el-table-column>
        <el-table-column label="资金用途" align="center" prop="capital_use">
          <template slot-scope="scope">{{ scope.row.capital_use || '-' }}</template>
        </el-table-column>
        <el-table-column prop="funds" label="金额(万元)" align="center">
          <template slot-scope="scope">{{ scope.row.funds || '-' }}</template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center">
          <template slot-scope="scope">{{ scope.row.remark || '-' }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" v-if="noFile">
          <template slot-scope="scope" v-if="scope.row.submit_type !== '1'">
            <el-tooltip effect="dark" content="修改" placement="bottom">
              <el-button type="text" style="font-size: 20px" @click="edit(scope.row)">
                <i class="fa fa-edit"></i>
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="bottom">
              <el-button
                type="text"
                @click="deleteData(scope.row)"
                style="font-size: 20px; color: red"
              >
                <i class="fa fa-trash"></i>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </loading-wrap>

    <el-dialog
      title="资金来源明细"
      width="80%"
      :close-on-click-modal="false"
      :before-close="breakdownClose"
      :visible.sync="breakdownVisible"
    >
      <el-table :data="breakdownData" v-loading="breakloading" border>
        <el-table-column label="资金来源" align="center">
          <template slot-scope="scope">
            <select-facname
              multiple
              filterable
              allow-create
              v-model="scope.row.capital_source"
            ></select-facname>
          </template>
        </el-table-column>
        <el-table-column label="资金用途" align="center">
          <template slot-scope="scope">
            <el-input placeholder="资金用途" v-model="scope.row.capital_use"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="金额(万元)" align="center">
          <template slot-scope="scope">
            <el-input placeholder="金额" v-model="scope.row.funds"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template slot-scope="scope">
            <el-input placeholder="备注" v-model="scope.row.remark"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="60px">
          <template slot-scope="scope">
            <el-button type="text" class="py-0 px-1 text-danger" @click="deleteArray(scope.$index)">
              <i class="fa fa-trash"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-3">
        <el-row :gutter="20">
          <el-col :span="3">
            <el-button @click="breakdownData.push({})">新增一行</el-button>
          </el-col>
          <el-col :span="2">
            <el-button @click="breakdownClose" style="width: 100%">取消</el-button>
          </el-col>
          <el-col :span="2">
            <el-button @click="breakdoenSubmit" :loading="breakloading" style="width: 100%">
              <span>保存</span>
            </el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <form-component
      :visible.sync="editVisible"
      ref="fc"
      :table-name="tableName"
      :form-data="formData"
      :table-id="tableId"
      :table-data="editData"
      :auto-init="false"
      @success="getsourcesData"
    ></form-component>

    <div class="d-flex mb-3" style="margin-top: 30px">
      <h5 class="card-title">新增项目投入明细</h5>
      <button class="btn pt-0 btn-text text-muted" @click="inputdetail()" v-if="noFile">
        <i class="fa fa-edit"></i>
      </button>
    </div>

    <table class="table table-bordered bg-white">
      <colgroup>
        <col width="14%" />
        <col width="14%" />
        <col width="14%" />
        <col width="14%" />
        <col width="14%" />
        <col width="15%" />
        <col width="15%" />
      </colgroup>
      <tbody>
        <tr class="text-center">
          <td :colspan="6 + colspan">项目固定投入明细</td>
        </tr>
        <tr class="text-center">
          <td>项目</td>
          <td>数量</td>
          <td>单位</td>
          <td>单价（元）</td>
          <td>金额（万元）</td>
          <td :colspan="colspan">备注</td>
          <td v-if="noFile">操作</td>
        </tr>
        <tr v-for="(p, index) of fixedData" :key="`two-` + index" class="text-center">
          <td>{{ p.project_name || '-' }}</td>
          <td>{{ p.scale || '-' }}</td>
          <td>{{ p.uscale || '-' }}</td>
          <td>{{ p.unit_price || '-' }}</td>
          <td>{{ p.funds || '-' }}</td>
          <td :colspan="colspan">{{ p.remark || '-' }}</td>
          <td v-if="noFile">
            <el-tooltip effect="dark" content="修改" placement="bottom">
              <el-button type="text" style="font-size: 15px" @click="fixed(fixedData[index])">
                <i class="fa fa-edit"></i>
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="bottom">
              <el-button
                type="text"
                @click="deleteflowData(fixedData[index], 'fixedData')"
                style="font-size: 15px; color: red"
              >
                <i class="fa fa-trash"></i>
              </el-button>
            </el-tooltip>
          </td>
        </tr>
        <tr class="text-center">
          <td>合计</td>
          <td>-</td>
          <td>—</td>
          <td>—</td>
          <td>{{ fundsAll }} 万元</td>
          <td :colspan="colspan">-</td>
          <td v-if="noFile">-</td>
        </tr>
        <tr class="text-center">
          <td colspan="7">项目流动资金投入明细</td>
        </tr>
        <tr class="text-center">
          <td>项目</td>
          <td>数量</td>
          <td>单位</td>
          <td>单价（元）</td>
          <td>金额（万元）</td>
          <td :colspan="colspan">备注</td>
          <td v-if="noFile">操作</td>
        </tr>
        <tr v-for="(p, index) of flowData" :key="`floo-` + index" class="text-center">
          <td>{{ p.project_name || '-' }}</td>
          <td>{{ p.scale || '-' }}</td>
          <td>{{ p.uscale || '-' }}</td>
          <td>{{ p.unit_price || '-' }}</td>
          <td>{{ p.funds || '-' }}</td>
          <td :colspan="colspan">{{ p.remark }}</td>
          <td v-if="noFile">
            <el-tooltip effect="dark" content="修改" placement="bottom">
              <el-button type="text" style="font-size: 15px" @click="flow(flowData[index])">
                <i class="fa fa-edit"></i>
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="bottom">
              <el-button
                type="text"
                @click="deleteflowData(flowData[index], 'flowData')"
                style="font-size: 15px; color: red"
              >
                <i class="fa fa-trash"></i>
              </el-button>
            </el-tooltip>
          </td>
        </tr>
        <tr class="text-center">
          <td>合计</td>
          <td>-</td>
          <td>—</td>
          <td>—</td>
          <td>{{ flowfundsAll }} 万元</td>
          <td :colspan="colspan">-</td>
          <td v-if="noFile">-</td>
        </tr>
      </tbody>
    </table>
    <form-component
      :visible.sync="fixedVisible"
      ref="fx"
      :form-data="fixedformData"
      :table-id="flowId"
      :table-name="flowName"
      :table-data="floweditData"
      :auto-init="false"
      @success="getflowData"
    ></form-component>

    <form-component
      :visible.sync="flowVisible"
      ref="fc"
      :table-name="flowName"
      :form-data="flowformData"
      :table-id="flowId"
      :table-data="floweditData"
      :auto-init="false"
      @success="getflowData"
    ></form-component>

    <el-dialog
      title="项目投入明细"
      width="80%"
      :close-on-click-modal="false"
      :before-close="inputClose"
      :visible.sync="inputVisible"
    >
      <el-table :data="inputdetailData" v-loading="inputloading" border>
        <el-table-column label="类型" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.input_type">
              <el-option key="1" label="固定资产投入" value="1"></el-option>
              <el-option key="2" label="项目流动资金投入" value="2"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <!--<el-table-column label="项目" align="center">-->
        <!--<template slot-scope="scope">-->
        <!--<select-facname  multiple filterable  allow-create v-model="scope.row.project_name"></select-facname>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column label="项目" align="center">
          <template slot-scope="scope">
            <el-autocomplete
              v-model="scope.row.project_name"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入或选择项目"
              @select="handleSelect"
            ></el-autocomplete>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center">
          <template slot-scope="scope">
            <el-input
              placeholder="数量"
              v-model="scope.row.scale"
              @input="handleCalcTotal(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center">
          <template slot-scope="scope">
            <select-unitof v-model="scope.row.uscale"></select-unitof>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center">
          <template slot-scope="scope">
            <el-input
              placeholder="单价"
              v-model="scope.row.unit_price"
              @input="handleCalcTotal(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="金额(万元)" align="center">
          <template slot-scope="scope">
            <el-input placeholder="金额(万元)" v-model="scope.row.funds"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template slot-scope="scope">
            <el-input placeholder="备注" v-model="scope.row.remark"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="60px">
          <template slot-scope="scope">
            <el-button type="text" class="py-0 px-1 text-danger" @click="deleteIput(scope.$index)">
              <i class="fa fa-trash"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-3" v-loading="inputloading">
        <el-row :gutter="20">
          <el-col :span="3">
            <el-button @click="inputdetailData.push({})">新增一行</el-button>
          </el-col>
          <el-col :span="2">
            <el-button @click="inputClose" style="width: 100%">取消</el-button>
          </el-col>
          <el-col :span="2">
            <el-button @click="inputSubmit" style="width: 100%"><span>保存</span></el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { enumFinanceSourceType, enumFinanceInputType, enumInputtype } from '@/credit/plugins/enum'
import FormComponent from '@/components/FormComponent'
import SelectFacname from '@/credit/components/select/SelectCapitalsource'
import SelectUnitof from '@/credit/components/select/SelectUnitof'
export default {
  components: {
    FormComponent,
    SelectFacname,
    SelectUnitof,
  },
  props: {},
  data() {
    return {
      enumInputtype,
      // 项目固定投入明细
      inputVisible: false,
      inputdetailData: [{}, {}],
      inputloading: false,
      fixedformData: {
        input_type: {
          type: 'radio',
          label: '类型',
          value: '1',
          enumType: enumInputtype,
          inline: true,
        },
        project_name: {
          type: 'dropdown',
          value: '',
          label: '项目名称',
          required: true,
          enumType: enumFinanceInputType,
        },
        scale: {
          type: 'number',
          value: '',
          label: '数量',
          step: 0.01,
          onInput: (k, v, i) => {
            const fx = this.$refs.fx
            if (!fx) {
              return
            }
            const scale = this.getNumber(v)
            const price = this.getNumber(i.unit_price.value)
            fx.setKey('funds', 'value', this.fixZero((scale * price) / 10000))
          },
        },
        uscale: {
          type: 'component',
          label: '单位',
          value: '',
          component: SelectUnitof,
          attrs: { css: 'form-control-ml' },
        },
        unit_price: {
          type: 'number',
          value: '',
          label: '单价',
          step: 0.01,
          onInput: (k, v, i) => {
            const fx = this.$refs.fx
            if (!fx) {
              return
            }
            const price = this.getNumber(v)
            const scale = this.getNumber(i.scale.value)
            fx.setKey('funds', 'value', this.fixZero((scale * price) / 10000))
          },
        },
        funds: {
          type: 'number',
          value: '',
          label: '金额',
          required: true,
          unit: '万元',
          step: 0.0001,
        },
        remark: { type: 'textarea', value: '', label: '备注', maxWidth: true },
      },
      fixedData: [],
      fixData: {},
      fixedVisible: false,
      // 项目资金投入明细
      enumFinanceInputType,
      flowData: [],
      flowVisible: false,
      flowName: 'datum_customer_finance_project_input',
      flowId: '',
      floweditData: {},
      flowformData: {
        input_type: {
          type: 'radio',
          label: '类型',
          value: '2',
          enumType: enumInputtype,
          inline: true,
        },
        project_name: {
          type: 'dropdown',
          value: '',
          label: '项目名称',
          required: true,
          enumType: enumFinanceInputType,
        },
        scale: {
          type: 'number',
          value: '',
          label: '数量',
          step: 0.01,
          onInput: (k, v, i) => {
            const fc = this.$refs.fc
            if (!fc) {
              return
            }
            const scale = this.getNumber(v)
            const price = this.getNumber(i.unit_price.value)
            fc.setKey('funds', 'value', this.fixZero((scale * price) / 10000))
          },
        },
        uscale: {
          type: 'component',
          label: '单位',
          value: '',
          component: SelectUnitof,
          attrs: { css: 'form-control-ml' },
        },
        unit_price: {
          type: 'number',
          value: '',
          label: '单价',
          step: 0.01,
          onInput: (k, v, i) => {
            const fc = this.$refs.fc
            if (!fc) {
              return
            }
            const price = this.getNumber(v)
            const scale = this.getNumber(i.scale.value)
            fc.setKey('funds', 'value', this.fixZero((scale * price) / 10000))
          },
        },
        funds: {
          type: 'number',
          value: '',
          label: '金额',
          required: true,
          unit: '万元',
          step: 0.0001,
        },
        remark: { type: 'textarea', value: '', label: '备注', maxWidth: true },
      },
      // 资金来源明细
      enumFinanceSourceType,
      sourcesData: [],
      editVisible: false,
      breakdownVisible: false,
      breakloading: false,
      breakdownData: [{}],
      tableName: 'datum_customer_finance_capital_source',
      tableId: '',
      editData: {},
      formData: {
        capital_source_key: {
          type: 'radio',
          value: '1',
          label: 'type',
          required: true,
          enumType: enumFinanceSourceType,
          inline: true,
          hide: true,
          redundancy: fc =>
            this.$utils.findKeyFromValue(enumFinanceSourceType, fc.capital_source.value, 'other'),
        },
        capital_source: {
          type: 'component',
          label: '资金来源',
          value: '',
          component: SelectFacname,
          required: true,
        },
        funds: { type: 'number', label: '金额', value: '', unit: '万元', required: true, step: 1 },
        capital_use: { type: 'text', label: '资金用途', value: '' },
        remark: { type: 'text', label: '备注', value: '' },
      },
      fundsAll: 0,
      flowfundsAll: 0,
      restaurants: [],
      timeout: null,
      colspan: 1,
      //
      customerData: {},
    }
  },
  computed: {
    noFile() {
      return this.customerData.project_status !== '1' || this.customerData.project_status === '3'
    },
  },
  watch: {},
  created() {
    this.customerData = JSON.parse(sessionStorage.getItem('customer_related_view'))
    this.id = this.$route.query.id || sessionStorage.getItem('customer_related_id')
    this.getData()
  },
  mounted() {
    this.restaurants = this.loadAll()
  },
  methods: {
    loadAll() {
      return [
        { key: 'water', value: '水' },
        { key: 'electric', value: '电' },
        { key: 'agri_insurance', value: '农业保险' },
        { key: 'other', value: '其它' },
      ]
    },
    querySearchAsync(queryString, cb) {
      const restaurants = this.restaurants
      const results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants

      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(results)
      }, 500 * Math.random())
    },
    createStateFilter(queryString) {
      return state => {
        return state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      }
    },
    handleSelect() {},
    getNumber(num) {
      const n = Number.parseFloat(num)
      return isNaN(n) ? 0 : n
    },
    fixZero(num) {
      return Math.round(num * 10000) / 10000
    },
    getData() {
      if (this.customerData.project_status === '1' || this.customerData.project_status === '3') {
        this.colspan = 2
      }
      this.getsourcesData()
      this.getflowData()
    },
    getflowData() {
      this.flowfundsAll = 0
      this.fundsAll = 0
      this.fixedData = []
      this.flowData = []
      this.$api
        .getData('credit', this.flowName, {
          'customer_related_id.eq': this.id,
        })
        .then(res => {
          if (!res.data) {
            return
          }
          let solidTotal = 0
          let flowTotal = 0
          for (const d of res.data) {
            const t = Number.parseFloat(d.funds)
            const o = isNaN(t) ? 0 : t
            if (d.input_type === '1') {
              this.fixedData.push(d)
              solidTotal += o
            } else {
              this.flowData.push(d)
              flowTotal += o
            }
          }
          this.fundsAll = Math.round(solidTotal * 10000) / 10000
          this.flowfundsAll = Math.round(flowTotal * 10000) / 10000
        })
    },
    getsourcesData() {
      this.sourcesData = []
      this.$api
        .getData('credit', this.tableName, {
          'customer_related_id.eq': this.id,
        })
        .then(res => {
          this.sourcesData = res.data
        })
    },
    edit(p) {
      this.editVisible = true
      this.tableId = p ? p.id : ''
      this.editData = p
    },
    deleteArray(index) {
      this.breakdownData.splice(index, 1)
    },
    breakdown() {
      this.breakdownVisible = true
      this.breakdownData = [{}, {}]
    },
    breakdownClose() {
      this.breakdownVisible = false
    },
    inputdetail() {
      this.inputVisible = true
      this.inputdetailData = [{}, {}]
    },
    deleteIput(index) {
      this.inputdetailData.splice(index, 1)
    },
    inputClose() {
      this.inputVisible = false
    },
    fixed(p) {
      this.fixedVisible = true
      this.flowId = p ? p.id : ''
      this.floweditData = p
    },
    flow(p) {
      this.flowVisible = true
      this.flowId = p ? p.id : ''
      this.floweditData = p
    },
    breakdoenSubmit() {
      let data = []
      for (let p of this.breakdownData) {
        if (JSON.stringify(p) !== '{}') {
          p.customer_id = this.customerData.customer_id
          p.customer_name = this.customerData.customer_name
          p.customer_related_id = this.id
          p.capital_source_key = this.$utils.findKeyFromValue(
            enumFinanceSourceType,
            p.capital_source.value,
            'other'
          )
          data.push(p)
        }
      }
      if (data.length > 0) {
        this.toBreakdown(data)
      } else {
        this.$message.warning('请输入信息！')
      }
    },
    async toBreakdown(data) {
      this.breakloading = true
      const [res, err] = await this.$utils.promise(
        this.$api.addBatch('credit', this.tableName, data)
      )
      this.breakloading = false
      if (res) {
        this.$message.success('数据采集成功！')
        this.getsourcesData()
        this.breakdownClose()
        this.breakdownData = []
      } else {
        this.$message.error(`数据采集失败，请重试！（${err.status}）`)
      }
    },
    inputSubmit() {
      let data = []
      for (let p of this.inputdetailData) {
        if (JSON.stringify(p) !== '{}') {
          p.customer_id = this.customerData.customer_id
          p.customer_name = this.customerData.customer_name
          p.customer_related_id = this.id
          data.push(p)
        }
      }
      if (data.length > 0) {
        this.toInputdetail(data)
      } else {
        this.$message.warning('请输入信息！')
      }
    },
    async toInputdetail(data) {
      this.inputloading = true
      const [res, err] = await this.$utils.promise(
        this.$api.addBatch('credit', this.flowName, data)
      )
      this.inputloading = false
      if (res) {
        this.$message.success('数据采集成功！')
        this.getflowData()
        this.inputClose()
        this.inputdetailData = []
      } else {
        this.$message.error(`数据采集失败，请重试！（${err.status}）`)
      }
    },
    deleteData(item) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定删除？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            const [res] = await this.$utils.promise(
              this.$api.deleteData('credit', this.tableName, item.id)
            )
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('删除成功！')
              this.getData()
              done()
            } else {
              this.$message.error('删除失败，请重试！')
            }
          } else {
            done()
          }
        },
      }).catch(() => {})
    },
    deleteflowData(item, key) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定删除？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            let res = ''
            if (key === 'fixedData') {
              res = await this.$utils.promise(
                this.$api.deleteData('credit', this.flowName, item.id)
              )
            } else {
              res = await this.$utils.promise(
                this.$api.deleteData('credit', this.flowName, item.id)
              )
            }
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('删除成功！')
              this.getflowData()
              done()
            } else {
              this.$message.error('删除失败，请重试！')
            }
          } else {
            done()
          }
        },
      }).catch(() => {})
    },

    handleCalcTotal(row) {
      const scale = this.getNumber(row.scale)
      const price = this.getNumber(row.unit_price)
      row.funds = this.fixZero((scale * price) / 10000)
    },
  },
}
</script>
<style scoped></style>
